<?php
class Router {
    private $_uriString;
    private $_uriParams;
    
    function __construct() {
        if( isset( $_SERVER['SCRIPT_NAME'] ) && isset( $_SERVER['REQUEST_URI'] ) )
            $this -> _uriString = trim( preg_replace( '#' . preg_quote( URLPATH ) . '#i', '', $_SERVER['REQUEST_URI'], 1 ), '/' );
        
        $this -> _uriParams = array_merge( $this -> _pathInfo(), $this -> _queryString() );
    }//end __construct
    
    function getUriString() {
        return $this -> _uriString;
    }
    
    function getUriParams() {
        return $this -> _uriParams;
    }
    
    function error404() {
        ob_end_clean();
        header('HTTP/1.1 404 Not Found');
        include( ERRORS_PATH . '404' . PHP_EX );
        exit;
    }
    
    private function _pathInfo() {
        if( isset( $_SERVER['PATH_INFO'] ) && ( $path_info = trim( $_SERVER['PATH_INFO'], '/' ) ) != '' ) {
            $tmp = explode( '/', $path_info );
            $path[ 'controller_name' ] = array_shift( $tmp );
            $path[ 'controller_method' ] = array_shift( $tmp );
            reset( $tmp );
            do {
                $path[ current( $tmp ) ] = ($v = next( $tmp )) !== false ? $v : true;
            }while( next( $tmp ) );
            unset( $v );
            unset( $tmp );
        }else {
            $path[ 'controller_name' ] = false;
            $path[ 'controller_method' ] = false;
        }
        return $path;
    }
    
    private function _queryString() {
        $query_str = array( );
        if( isset( $_SERVER['QUERY_STRING'] ) )
            parse_str( $_SERVER['QUERY_STRING'], $query_str );
        return $query_str;
    }
}